//引入axios
import Vue from 'vue'
import axios from 'axios'
import store from '../store'
import router from '../router'
// 使用element-ui Message做消息提醒
import { Message } from 'element-ui';
//使用Toast做消息提示
import { Toast } from 'vant';

import { getToken} from '@/utils/auth'
Vue.use(Toast);

// 设置请求过期时间
axios.defaults.timeout = 10000

//请求拦截器
axios.interceptors.request.use(config => {

  config.headers = {
    'Content-Type': 'application/json'
  }
  // 配置token
  //需要授权的api必须在请求头中使用Authorization字段提供token令牌
  config.headers.Authorization = getToken()

  return config
}, error => {
  return Promise.reject(error)
})

//响应拦截器即异常处理
axios.interceptors.response.use(response => {

    switch(response.data.code) {
      //处理共有的操作
    }
    if(response.data.code === '1000'){
        //登陆过期 需要重新登陆 清空Cookie中的信息
        store.dispatch('user/logout').then(() => {

        })
        //跳转到login页面
        const toast = Toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true,
          message: '登录已失效，请重新登录',
        });
        
        let second = 3;
        const timer = setInterval(() => {
          second--;
          if (second) {
            toast.message = `倒计时 ${second} 秒`;
          } else {
            router.replace({path:'/login'})
            clearInterval(timer);
            // 手动清除 Toast
            Toast.clear();
          }
        }, 1000);
    }
  return response
}, error => {
  if(error && error.response) {
    switch(error.response.status) {
      case 400:
        error.message = '错误请求'
        break;
      case 401:
        error.message = '未授权，请重新登录'
        break;
      case 403:
        error.message = '没有权限，拒绝访问'
        break;
      case 404:
        error.message = '请求错误,未找到该资源'
        break;
      case 405:
        error.message = '请求方法未允许'
        break;
      case 408:
        error.message = '请求超时'
        break;
      case 500:
        error.message = '服务器端出错'
        break;
      case 501:
        error.message = '网络未实现'
        break;
      case 502:
        error.message = '网络错误'
        break;
      case 503:
        error.message = '服务不可用'
        break;
      case 504:
        error.message = '网络超时'
        break;
      case 505:
        error.message = 'http版本不支持该请求'
        break;
      default:
        error.message = `连接错误${error.response.status}`
    }
  } else {
    error.message = "连接到服务器失败"
  }

  Message.error(error.message)

  return Promise.resolve(error.response)
})

export default {

  /**
   *   get请求
   * @param {*} url 
   * @param {*} param 
   */
  get (url, param = {}) {
    return new Promise((resolve, reject) => {
      axios.get(url,{params:param})
        .then(res => {
          resolve(res)
        }, err => {
          reject(err)
        })
    })
  },
  /**
   * post请求
   * @param {*} url 
   * @param {*} param 
   */
  post (url, param = {}) {
    return new Promise((resolve, reject) => {
      axios.post(
        url,
        param
      ).then(res => {
        resolve(res)
      }, err => {
        reject(err)
      })
    })
  },
  /**
   * put请求
   * @param {*} url 
   * @param {*} param 
   */
  put (url, param = {}) {
    return new Promise((resolve, reject) => {
      axios.put(url, param)
        .then(response => {
          resolve(response)
        }, err => {
          reject(err)
        })
    })
  },
  /**
   * delete请求
   * @param {*} url 
   * @param {*} param 
   */
  delete (url,param = {}){
    return new Promise((resolve, reject) => {
      axios.delete(url, param)
        .then(response => {
          resolve(response)
        }, err => {
          reject(err)
        })
    })
  }
}

